package server.service.impl;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.MenuDao;
import server.dao.UsersDao;
import server.model.dto.MenuDto;
import server.model.entity.MenuEntity;
import server.model.entity.Users;
import server.service.MenuService;
import server.tool.tool.BeanUtil;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UsersDao usersDao;

    @Override
    public RetResult findAll(String userId) {
        Users users = usersDao.findById(userId).get();
        List<MenuEntity> entity = menuDao.findByStatusAndRoleId(true, users.getRole().getId());
        List<MenuDto> dto = Lists.newLinkedList();
        entity.stream().forEach(ls -> {
            dto.add(BeanUtil.convertToBean(ls, MenuDto.class));
        });
        return RetResponse.makeOKRsp(menuSort(dto));
    }

    private List<MenuDto> menuSort(List<MenuDto> menuDtos) {
        Map<Integer, List<MenuDto>> mp = menuDtos.stream()
                .collect(Collectors.groupingBy(MenuDto::getSeries));
        mp.keySet().stream().forEach(key -> {
            mp.get(key).stream().forEach(th -> {
                Optional.ofNullable(mp.get(key + 1)).orElseGet(() -> {
                    return Lists.newLinkedList();
                }).stream().forEach(son -> {
                    if (son.getParentId().equals(th.getId())) {
                        List<MenuDto> child = th.getChild() == null ? Lists.newLinkedList()
                                : th.getChild();
                        child.add(son);
                        th.setChild(child);
                    }
                });
            });
        });
        return mp.get(1);
    }


}
